<template>
  <div class="app-container">
    <el-tabs active-name="business" @tab-click="handleTabsClick">
      <el-tab-pane label="商机" name="business"></el-tab-pane>
      <el-tab-pane label="公海池" name="businessPool"></el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入客户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商机归属" prop="channel">
        <el-input
          v-model="queryParams.channel"
          placeholder="请输入商机归属"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="!queryParams.cluePool" label="状态" prop="status">
        <el-select clearable v-model="queryParams.status" placeholder="请选择状态">
          <el-option label="待跟进" value="0"></el-option>
          <el-option label="已分配" value="1"></el-option>
          <el-option label="跟进中" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期" prop="createTimeRange">
        <el-date-picker
          v-model="queryParams.createTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row v-if="!queryParams.businessPool" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="doAdd"
          v-hasPermi="['crm:business:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="doBatchAssign"
          v-hasPermi="['crm:assignRecord:add']"
        >批量分配</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['crm:business:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['crm:business:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:business:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="businessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" prop="id" />
      <el-table-column label="客户姓名" prop="name" />
      <el-table-column label="手机号" prop="phone" />
      <el-table-column label="归属人" prop="owner" />
      <el-table-column label="创建时间" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商机状态" :formatter="formatStatus"/>
      <el-table-column label="下次跟进时间" prop="nextTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.nextTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['crm:business:edit']"
          >查看</el-button>
          <el-button v-if="scope.row.status == '1' || scope.row.status == '2'"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleTrack(scope.row)"
                     v-hasPermi="['crm:business:edit']"
          >跟进</el-button>
          <el-button v-if="scope.row.status == '0' || scope.row.status == '1'"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="doAssign([scope.row.id])"
                     v-hasPermi="['crm:business:edit']"
          >分配</el-button>
          <el-button v-if="scope.row.status == '3' || scope.row.status == '4'"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="doReset(scope.row)"
                     v-hasPermi="['crm:business:edit']"
          >捞取</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商机对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="娓犻亾" prop="channel">
          <el-input v-model="form.channel" placeholder="请输入娓犻亾" />
        </el-form-item>
        <el-form-item label="活动id" prop="activityId">
          <el-input v-model="form.activityId" placeholder="请输入活动id" />
        </el-form-item>
        <el-form-item label="省" prop="provinces">
          <el-input v-model="form.provinces" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="区" prop="city">
          <el-input v-model="form.city" placeholder="请输入区" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="微信" prop="weixin">
          <el-input v-model="form.weixin" placeholder="请输入微信" />
        </el-form-item>
        <el-form-item label="qq" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入qq" />
        </el-form-item>
        <el-form-item label="意向等级" prop="level">
          <el-input v-model="form.level" placeholder="请输入意向等级" />
        </el-form-item>
        <el-form-item label="意向学科" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入意向学科" />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程" />
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="form.occupation" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-input v-model="form.education" placeholder="请输入学历" />
        </el-form-item>
        <el-form-item label="在职情况" prop="job">
          <el-input v-model="form.job" placeholder="请输入在职情况" />
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input v-model="form.salary" placeholder="请输入薪资" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="form.major" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="希望薪资" prop="expectedSalary">
          <el-input v-model="form.expectedSalary" placeholder="请输入希望薪资" />
        </el-form-item>
        <el-form-item label="学习原因" prop="reasons">
          <el-input v-model="form.reasons" placeholder="请输入学习原因" />
        </el-form-item>
        <el-form-item label="职业计划" prop="plan">
          <el-input v-model="form.plan" placeholder="请输入职业计划" />
        </el-form-item>
        <el-form-item label="计划时间" prop="planTime">
          <el-date-picker clearable
                          v-model="form.planTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="其他意向" prop="otherIntention">
          <el-input v-model="form.otherIntention" placeholder="请输入其他意向" />
        </el-form-item>
        <el-form-item label="${comment}" prop="nextTime">
          <el-date-picker clearable
                          v-model="form.nextTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择${comment}">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="${comment}" prop="lastUpdateTime">
          <el-date-picker clearable
                          v-model="form.lastUpdateTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择${comment}">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="${comment}" prop="clueId">
          <el-input v-model="form.clueId" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="是否转派" prop="transfer">
          <el-input v-model="form.transfer" placeholder="请输入是否转派" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="回收时间" prop="endTime">
          <el-date-picker clearable
                          v-model="form.endTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择回收时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <assign-dialog  ref="assignDialog"
                    :type="assignType"
                    :title="assignTitle"
                    @success="getList"></assign-dialog>
    <el-drawer
      :visible.sync="drawer"
      :withHeader="false"
      :open="handleDrawerOpen"
      :destroy-on-close="true"
      size="70%"
      ref="trackDrawerRef"
    >
      <business-track :businessId="businessId" :disabled="viewFlag" ref="trackRef" @success="getList" @cancel="closeTrackDrawer"></business-track>
    </el-drawer>
  </div>
</template>

<script>
  import { listBusiness, getBusiness, delBusiness, addBusiness, updateBusiness } from "@/api/crm/business";
  import { resetBusiness } from "@/api/crm/businessTrack";
  import AssignDialog from '@/views/crm/business/operation/assign'
  import BusinessTrack from '@/views/crm/business/operation/track'

export default {
  name: "Business",
  dicts: ['sys_normal_disable','clue_status', 'clues_item', 'sys_user_sex', 'clues_level', 'course_subject'],
  components: { AssignDialog, BusinessTrack },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      businessList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        status: null,
        businessId: null,
        endTime: null,
        statusList: ["0", "1", "2"],
        createTimeRange: null,
        businessPool: false,
        orderByColumn: 'createTime',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      assignType: 'BUSINESS',
      assignTitle: '商机',
      drawer: false,
      businessId: null,
      viewFlag: false,
    };
  },
  created() {
    console.log("business index created...");
    this.getList();
  },
  methods: {
    /** 查询线索列表 */
    getList() {
      this.loading = true;
      //
      if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length == 2) {
        this.queryParams.createTimeRange[0] = this.parseTime(this.queryParams.createTimeRange[0])
        this.queryParams.createTimeRange[1] = this.parseTime(this.queryParams.createTimeRange[1])
      }
      if (!this.queryParams.statusList || this.queryParams.statusList.length == 0) {
        this.queryParams.statusList = ["0","1","2"];
      }
      listBusiness(this.queryParams).then(response => {
        this.businessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        phone: null,
        channel: null,
        activityId: null,
        provinces: null,
        city: null,
        sex: null,
        age: null,
        weixin: null,
        qq: null,
        level: null,
        subject: null,
        courseId: null,
        createBy: null,
        createTime: null,
        occupation: null,
        education: null,
        job: null,
        salary: null,
        major: null,
        expectedSalary: null,
        reasons: null,
        plan: null,
        planTime: null,
        otherIntention: null,
        status: "0",
        nextTime: null,
        lastUpdateTime: null,
        clueId: null,
        transfer: null,
        remark: null,
        endTime: null,

        price: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.status = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    doAdd() {
      this.reset();
      this.open = true;
      this.title = "添加线索";
    },
    /** 修改按钮操作 */

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBusiness(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBusiness(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 分配按钮操作 */
    doAssign(ids) {
      this.$refs.assignDialog.open = true
      this.$refs.assignDialog.form.assignIds = ids;
    },
    doBatchAssign() {
      if(this.ids.length == 0) {
        this.$modal.alert('请至少选择一条数据')
      } else {
        this.doAssign(this.ids);
      }
    },
    doReset(row) {
      this.$modal.confirm(`确定捞取商机[${row.id}]吗？`).then(() =>{
        resetBusiness({id: row.id, 'record': '重新捞取商机', userName: this.$store.getters.name})
          .then(resp=> {
            this.$modal.msgSuccess('捞取成功')
            this.getList()
          })
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/business/export', {
        ...this.queryParams
      }, `business_${new Date().getTime()}.xlsx`)
    },
    handleView(row) {
      this.viewFlag = true;
      this.handleTrack(row)
    },
    handleTrack(row) {
      this.businessId = row.id;
      this.drawer = true;
    },
    handleDrawerOpen() {
      // this.$refs.trackRef.clueId = this.clueId;
    },
    closeTrackDrawer() {
      this.drawer = false;
      this.viewFlag = false;
    },

    handleTabsClick(tab) {
      this.queryParams.businessPool = tab.name == 'businessPool'
      this.queryParams.businessPool ? this.queryParams.statusList = ['3', '4'] : this.queryParams.statusList = ['0', '1', '2'];
      if (this.queryParams.businessPool) {
        this.resetQuery();
      }
      this.getList();
    },
    formatStatus(row) {
      let status = this.selectDictLabel(this.dict.type.clue_status, row.status)
      return status == '伪线索' ? '踢回公海' : status
    }
  }
};
</script>
<style scoped>
  .app-container {
    padding:5px 5px 15px 5px;
  }
</style>
